﻿/* Write a program that reads a list of words from a file words.txt and 
 * finds how many times each of the words is contained in another file test.txt. 
 * The result should be written in the file result.txt and the words should be sorted by the 
 * number of their occurrences in descending order. 
 * Handle all possible exceptions in your methods.
 */

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace _13.ReadList
{
    class ReadList
    {
        static void Main()
        {
            Console.Write("Path to text file: ");
            string path_to_file = Console.ReadLine();
            Console.Write("Path to text file which contains words to be counted: ");
            string path_to_file2 = Console.ReadLine();

            try
            {
                /* read files */
                StreamReader SR = new StreamReader(@path_to_file);
                string line = SR.ReadLine();

                string[] wordlist1 = File.ReadAllLines(path_to_file);
                string[] wordlist2 = File.ReadAllLines(path_to_file2);

                int counter = 0;
                StringBuilder sb = new StringBuilder();
                foreach (var v in wordlist1)
                {
                    sb.Append("\"");
                    sb.Append(v);
                    sb.Append("\" : ");
                    counter = 0;
                    foreach (var item in wordlist2)
                    {
                        if (item == v)
                            counter++;
                    }
                    sb.Append("+");
                    sb.Append(counter);
                    sb.AppendLine(" times");
                }
                Array.Sort(wordlist2);
                File.WriteAllText(@"../../result.txt", sb.ToString());
            }
            catch (FileNotFoundException f2)
            {
                throw new FileNotFoundException("The specified file could not be found" + f2.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
            }
            Console.WriteLine("Data successfully written.");
        }
    }
}
